package com.yuenov.open.utils;

import android.content.Context;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

public class FileDownload {

    /**
     * 文件夹路径
     */
    private static final String fileDirPath = "/sdcard/AKOSTAL";
    /**
     * 文件名
     */
    private static final String fileName = "logInfo.csv";

    /**
     * 将数据存到文件中
     *
     * @param context  context
     * @param data     需要保存的数据
     * @param fileName 文件名
     */
    public static void saveDataToFile(Context context, String data, String fileName) {

        File filesDir = context.getFilesDir();
        // 动态获得路径
        File file = new File(filesDir, "qqlogin.txt");
        // 输出流，把数据输出到文件中
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(file);
            // 写入字节流
            fos.write(data.getBytes());
            // 清空缓存
            fos.flush();
            // 关闭流
            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }


        FileOutputStream fileOutputStream = null;
        BufferedWriter bufferedWriter = null;
        try {
            /**
             * "data"为文件名,MODE_PRIVATE表示如果存在同名文件则覆盖，
             * 还有一个MODE_APPEND表示如果存在同名文件则会往里面追加内容
             */
            fileOutputStream = context.openFileOutput(fileName, Context.MODE_PRIVATE);
            bufferedWriter = new BufferedWriter(new OutputStreamWriter(fileOutputStream));
            bufferedWriter.write(data);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (bufferedWriter != null) {
                    bufferedWriter.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 从文件中读取数据
     *
     * @param context  context
     * @param fileName 文件名
     * @return 从文件中读取的数据
     */
    public static String loadDataFromFile(Context context, String fileName) {
        FileInputStream fileInputStream = null;
        BufferedReader bufferedReader = null;
        StringBuilder stringBuilder = new StringBuilder();
        try {
            /**
             * 注意这里的fileName不要用绝对路径，只需要文件名就可以了，系统会自动到data目录下去加载这个文件
             */
            fileInputStream = context.openFileInput(fileName);
            bufferedReader = new BufferedReader(new InputStreamReader(fileInputStream));
            String result = "";
            while ((result = bufferedReader.readLine()) != null) {
                stringBuilder.append(result);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bufferedReader != null) {
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return stringBuilder.toString();
    }

    /**
     * 把文件存储在内部，不可以导出
     **/
    public static void writeTheftDate(Context context, String msg) {
        // 步骤1：获取输入值
        if (msg == null) return;
        try {
            // 步骤2:创建一个FileOutputStream对象,MODE_APPEND追加模式
            FileOutputStream fos = context.openFileOutput("theftdatefile.txt", context.MODE_APPEND);
            // 步骤3：将获取过来的值放入文件
            fos.write(msg.getBytes());
            // 步骤4：关闭数据流
            fos.close();
        } catch (Exception e) {
            //e.printStackTrace();
        }
    }


    // 读取数据
    public String readTheftDate(Context context) {
        try {
            FileInputStream inStream = context.openFileInput("theftdatefile.txt");
            byte[] buffer = new byte[1024];
            int hasRead = 0;
            StringBuilder sb = new StringBuilder();
            while ((hasRead = inStream.read(buffer)) != -1) {
                sb.append(new String(buffer, 0, hasRead));
            }

            inStream.close();
            return sb.toString();
        } catch (Exception e) {
            //e.printStackTrace();
        }
        return null;
    }

    /**
     * 把文件存储在外部，可以导出
     **/
    public static void createFileAndSave(String route,String bookName, String str, String fileName) {

        String path = route + "/ShengXu/";
        //先实例化一个file对象，参数为路径名
        File file = new File(path + fileName);
        try {
//            if (file.exists()) { // 已经存在 直接写入文件
//                FileWriter write = new FileWriter(file, true);
//                BufferedWriter bufferedWriter = new BufferedWriter(write);
//                bufferedWriter.write(str);
//                bufferedWriter.newLine();//换行
//                bufferedWriter.flush();
//                write.close();
//                bufferedWriter.close();
//            } else {
            if (file.exists())
                file.delete();
            file = new File(path);
            if (!file.exists())
                file.mkdir();// 创建文件夹
            System.out.println("result============" + file.getPath());
            file = new File(path + fileName);
            System.out.println("result2============" + file.getPath());
            if (!file.exists()) file.createNewFile();//创建文件
            // 写入文件
            FileWriter write = new FileWriter(file, true);
            BufferedWriter bufferedWriter = new BufferedWriter(write);
            bufferedWriter.write(str);
            bufferedWriter.newLine();//换行
            bufferedWriter.flush();
            write.close();
            bufferedWriter.close();
//            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    private int getChsAscii(String chs) {
        int asc = 0;
        try {
            byte[] bytes = chs.getBytes("gb2312");
            if (bytes == null || bytes.length > 2 || bytes.length <= 0) {
                throw new RuntimeException("illegal resource string");
            }
            if (bytes.length == 1) {
                asc = bytes[0];
            }
            if (bytes.length == 2) {
                int hightByte = 256 + bytes[0];
                int lowByte = 256 + bytes[1];
                asc = (256 * hightByte + lowByte) - 256 * 256;
            }
        } catch (Exception e) {
            System.out.println("ERROR:ChineseSpelling.class-getChsAscii(String chs)" + e);
        }
        return asc;
    }
}